<template>
  <el-card class="overview-container">
    <div class="header">
      <div class="title">{{ t("home.latestReport.title") }}</div>
      <div class="header-info">
        <span class="report-count">{{
          t("home.latestReport.weeklyUploadCount", { total })
        }}</span>
        <div class="filter-tabs">
          <el-radio-group v-model="activeTab" @change="handleTabChange">
            <el-radio :label="2">{{
              t("home.latestReport.sortByAttention")
            }}</el-radio>
            <el-radio :label="1">{{
              t("home.latestReport.sortByTime")
            }}</el-radio>
          </el-radio-group>
        </div>
        <el-link type="primary" class="view-more" @click="handleViewMore">{{
          t("home.latestReport.viewMore")
        }}</el-link>
      </div>
    </div>

    <div v-loading="loading" class="report-list">
      <div
        v-for="report in reportList"
        :key="report.reportId"
        class="report-card"
      >
        <!-- 用户信息 -->
        <div class="user-info">
          <div class="user-details">
            <div class="user-name">{{ report.userName }}</div>
            <div class="user-tags">
              <span class="tag executive-tag">{{
                report.familyMemberName
              }}</span>
              <span
                :class="{
                  'health-tag': true,
                  'health-tag--sub': report.healthCategory === '亚健康人群',
                  'health-tag--normal': report.healthCategory === '健康人群',
                  'health-tag--chronic':
                    report.healthCategory === '慢性病人群' ||
                    report.healthCategory === '院外恢复期人群' ||
                    report.healthCategory === '院外康复期人群',
                  'health-tag--doctor':
                    report.healthCategory === '门诊就医人群' ||
                    report.healthCategory === '急诊就医人群',
                  'health-tag--hospital':
                    report.healthCategory === '住院就医人群'
                }"
              >
                {{ report.healthCategory }}
              </span>
            </div>
          </div>
          <!-- 星级评分 -->
          <div class="rating">
            <EditableRate
              v-model="report.attentionLevel"
              :data-type="1"
              :data-id="report.reportId"
            />
          </div>
        </div>

        <!-- 体检信息 -->
        <div class="exam-info">
          <div class="exam-detail">
            <span class="exam-type">{{ report.institution }}</span>
            <span class="exam-date"
              >{{ t("home.latestReport.medicalReport")
              }}{{ formatDate(report.inspectionDate) }}</span
            >
          </div>
        </div>

        <!-- 健康标签 -->
        <div class="health-tags">
          <span
            v-for="indicator in report.abnormalIndicators"
            :key="indicator.itemId"
            class="health-tag warning"
          >
            {{ indicator.name }}
          </span>
        </div>

        <!-- 风险描述 -->
        <div class="risk-description">
          <div class="risk-level">
            {{ t("home.latestReport.risk") }}{{ report.riskLevel }}
          </div>
          <div class="risk-detail">
            {{ getHealthDescription(report.abnormalIndicators) }}
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-link
            type="primary"
            size="small"
            @click="handleViewReport(report)"
          >
            {{ t("home.latestReport.actions.viewReport") }}
          </el-link>
          <el-link
            type="primary"
            size="small"
            @click="handleViewComparison(report)"
          >
            {{ t("home.latestReport.actions.compareReport") }}
          </el-link>
          <el-link
            type="primary"
            size="small"
            @click="handleViewSuggestion(report)"
          >
            {{ t("home.latestReport.actions.writeSuggestion") }}
          </el-link>
          <el-link type="primary" size="small" @click="handleAddTask(report)">
            {{ t("home.latestReport.actions.addToTask") }}
          </el-link>
          <el-link
            type="primary"
            size="small"
            @click="handleViewFamilyReport(report)"
          >
            {{ t("home.latestReport.actions.viewFamilyReport") }}
          </el-link>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && reportList.length === 0" class="empty-state">
        <el-empty :description="t('home.latestReport.empty.noReportData')" />
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </el-card>

  <!-- 报告对比抽屉 -->
  <ReportCompareDrawer
    v-model="showCompareDrawer"
    :current-report="currentReport"
  />

  <Jiankang
    ref="addJKDrawerRef"
    :title="t('home.todoTask.taskTypes.healthAdvice')"
    @save="onJKSave"
  />

  <!-- <AddTask
    ref="addTaskDrawerRef"
    :title="t('home.todoTask.drawer.fillFollowupPlan')"
    @save="onAddTaskSave"
  /> -->
  <!-- 任务计划弹窗 -->
  <follow-dialog
    v-model:visible="addTaskDialogVisible"
    :mode="'create'"
    :task-data="[]"
  />
</template>

<script setup lang="ts">
import {
  homeApi,
  type AbnormalIndicatorItem,
  type ReportItem
} from "@/api/home";
import Jiankang from "@/components/jiankang/index.vue";
import { userKey } from "@/utils/auth";
import ReportCompareDrawer from "@/views/report/components/report-compare-drawer/index.vue";
import { storageLocal } from "@pureadmin/utils";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
// import AddTask from "@/components/AddTask/index.vue";
import FollowDialog from "@/views/followUpPlan/components/followDialog.vue";

const showCompareDrawer = ref(false);
// 响应式数据
const reportList = ref<ReportItem[]>([]);
const currentPage = ref(1);
const pageSize = ref(9); // 一行3个，显示3行
const total = ref(0);
const loading = ref(false);
const activeTab = ref(2);
const currentReport = ref<ReportItem>();
const addJKDrawerRef = ref();
const addTaskDialogVisible = ref();
// 路由
const router = useRouter();
// 国际化
const { t } = useI18n();

const userInfo = storageLocal().getItem(userKey);

// 计算属性
const sortType = computed(() => {
  return activeTab.value === 1 ? 1 : 2;
});

const handleViewMore = () => {
  router.push({
    path: "/report/index",
    query: {
      isHasDate: "hasDate"
    }
  });
};

const onJKSave = data => {
  console.log("保存健康信息:", data);
  ElMessage.success(t("followUpPlan.messages.createSuccess"));
};

const onAddTaskSave = data => {
  console.log("保存任务信息:", data);
  ElMessage.success(t("followUpPlan.messages.createSuccess"));
};

// 获取报告列表
const getReportList = async () => {
  try {
    loading.value = true;

    const params = {
      sortType: sortType.value,
      userId: userInfo?.userId
    };
    const response = await homeApi.getLatestReportList(params);

    if (response.code === 0 && response.data) {
      reportList.value = response.data;
      total.value = response.data.length;
    } else {
      ElMessage.error(response.message || "获取报告列表失败");
    }
  } catch (error) {
    console.error("获取报告列表失败:", error);
    ElMessage.error("获取报告列表失败");
  } finally {
    loading.value = false;
  }
};

// 工具函数
const formatDate = (dateString: string) => {
  return dayjs(dateString).format("YYYY-MM-DD");
};

// const getStarRating = (attentionLevel: number) => {
//   // 根据关注级别转换为星级评分 (1-5)
//   return Math.min(Math.max(attentionLevel, 1), 5);
// };

const getHealthDescription = (abnormalIndicators: AbnormalIndicatorItem[]) => {
  if (abnormalIndicators.length === 0) {
    return t("home.latestReport.healthDescriptions.normal");
  }

  const descriptions = abnormalIndicators
    .map(item => item.desc)
    .filter(Boolean);
  if (descriptions.length > 0) {
    return (
      descriptions.join("；") +
      t("home.latestReport.healthDescriptions.followUpSuffix")
    );
  }

  const names = abnormalIndicators.map(item => item.name);
  return `${names.join("、")}${t("home.latestReport.healthDescriptions.abnormalSuffix")}`;
};

// 事件处理函数
const handleTabChange = (tab: string | number) => {
  activeTab.value = Number(tab);
  currentPage.value = 1;
  getReportList();
};

const handleViewReport = (report: ReportItem) => {
  router.push({
    path: "/report/detail",
    query: {
      reportId: report.reportId,
      mode: "view"
    }
  });
};

const handleViewComparison = (report: ReportItem) => {
  showCompareDrawer.value = true;
  currentReport.value = report;
};

const handleViewSuggestion = (report: ReportItem) => {
  addJKDrawerRef.value?.open(report.reportId);
};

const handleAddTask = (report: ReportItem) => {
  // addTaskDrawerRef.value?.open(report.reportId);
  addTaskDialogVisible.value = true;
};

const handleViewFamilyReport = (report: ReportItem) => {
  router.push({
    path: "/report/family",
    query: { familyId: report.familyId }
  });
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  getReportList();
};

// 组件挂载时获取数据
onMounted(() => {
  getReportList();
});
</script>

<style lang="scss" scoped>
.overview-container {
  border-radius: 16px !important;
  margin-bottom: 16px;

  :deep(.el-card__body) {
    padding: 16px 0;
  }

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    padding: 0 16px;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      position: relative;
      padding-left: 12px;
      margin-right: 32px;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background: linear-gradient(270deg, #61fffb 0%, #65c8ff 100%);
        box-shadow: 0px 2px 16px 0px rgba(41, 127, 128, 0.06);
        border-radius: 2px;
      }
    }

    .header-info {
      display: flex;
      align-items: center;
      gap: 20px;

      .report-count {
        font-size: 14px;
        color: #666;
      }

      .view-more {
        font-size: 14px;
      }
    }
  }

  .report-list {
    padding: 0 16px;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    min-height: 200px;

    .report-card {
      width: calc((100% - 32px) / 3);
      background: #fff;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      padding: 20px;
      box-sizing: border-box;
      transition: box-shadow 0.3s;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .user-info {
        display: flex;
        align-items: flex-start;
        margin-bottom: 16px;

        .user-details {
          flex: 1;

          .user-name {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin-bottom: 8px;
          }

          .user-tags {
            display: flex;
            gap: 8px;

            .tag {
              font-size: 12px;
              padding: 2px 8px;
              border-radius: 4px;
              white-space: nowrap;

              &.executive-tag {
                background: linear-gradient(300deg, #65c8ff 0%, #61fffb 100%);
                box-shadow: 0px 2px 16px 0px rgba(41, 127, 128, 0.06);
                color: #125981;
              }

              &.health-manager-tag {
                background: rgba(82, 196, 26, 0.1);
                color: #52c41a;
              }

              &.special-manager-tag {
                background: rgba(255, 193, 7, 0.1);
                color: #ffc107;
              }
            }
          }
        }

        .rating {
          margin-left: auto;
        }
      }

      .exam-info {
        margin-bottom: 12px;

        .exam-detail {
          font-size: 14px;
          color: #666;

          .exam-type {
            margin-right: 16px;
          }
        }
      }

      .health-tags {
        display: block;
        margin-bottom: 12px;
        /* 强制单行显示，超出部分省略号 */
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;

        .health-tag {
          font-size: 12px;
          padding: 4px 8px;
          border-radius: 4px;
          white-space: nowrap;
          display: inline-block;
          margin-right: 8px;

          &.warning {
            background: #fff2f4;
            box-shadow: 0px 2px 16px 0px rgba(41, 127, 128, 0.06);
            font-size: 14px;
            color: #222222;
          }
        }
      }

      .risk-description {
        margin-bottom: 16px;

        .risk-level {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          margin-bottom: 4px;
        }

        .risk-detail {
          font-size: 14px;
          color: #666;
          line-height: 1.5;
          /* 新增：限制显示两行，超出部分省略号 */
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: break-word;
        }
      }

      .action-buttons {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;

        .el-link {
          font-size: 12px;
          padding: 4px 8px;
        }
      }
    }

    .empty-state {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 200px;
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }
}
</style>
